#include "BufferTestSuite.h"
#include <string>
#define UNIT_TEST
#include "BufferV2.h"

static xncc::foundation::BufferV2 buffer;

std::queue<char> BufferTestSuite::Tcpbuffer;
std::mutex       BufferTestSuite::TcpbufferMutex;
TEST_F(BufferTestSuite, fixLengthMessage)
{
    std::cout << " buffer size:" << buffer.size() << std::endl;

    const std::string msg           = "helloworld";
    constexpr int     MESSAGE_COUNT = 300;
    for (int i = 0; i < MESSAGE_COUNT; ++i) {
        SenMessageToSocket(msg);
    }
    MockClose();

    int read_count = 0;
    buffer.set_callback([&](const xncc::types::Header*, const char* body, std::size_t bodyLen) {
        read_count++;
        EXPECT_EQ(msg, std::string(body, bodyLen));
    });
    std::thread read_thread([&]() {
        while (true) {
            auto result = buffer.read_from_socket(-1);
            if (result < 0) {
                std::cout << "read from socket error  result:" << result << std::endl;
                break;
            }
        }
    });

    read_thread.join();

    EXPECT_EQ(MESSAGE_COUNT, read_count);
    std::cout << " buffer size:" << buffer.size() << std::endl;
}

TEST_F(BufferTestSuite, randomLengthMessage)
{
    std::queue<char> tmp_buffer;
    Tcpbuffer.swap(tmp_buffer);
    buffer.reset();
    std::cout << " buffer size:" << buffer.size() << std::endl;
    const std::string msg = "01234567890123456789";

    int read_count = 0;
    buffer.set_callback([&](const xncc::types::Header*, const char* body, std::size_t bodyLen) {
        EXPECT_EQ(msg + std::to_string(read_count * 10000), std::string(body, bodyLen));
        read_count++;
    });
    std::thread read_thread([&]() {
        while (true) {
            auto result = buffer.read_from_socket(-1);
            if (result < 0) {
                std::cout << "read from socket error  result:" << result << std::endl;
                break;
            }
        }
    });

    constexpr int MESSAGE_COUNT = 3000;
    for (int i = 0; i < MESSAGE_COUNT; ++i) {
        SenMessageToSocket(msg + std::to_string(i * 10000));
    }
    MockClose();

    read_thread.join();

    EXPECT_EQ(MESSAGE_COUNT, read_count);
    std::cout << " buffer size:" << buffer.size() << std::endl;
}
